package by.hqsoftware.RollingBall.GraphicElements;

import javax.microedition.khronos.opengles.GL10;

import android.util.Log;
import by.hqsoftware.RollingBall.Converter;

public class Field extends Mesh{

	public Field(Ball ball) {
		mBall = ball;
		mBall.setField(this);				
	}
	
	private Ball mBall;	
	private float mRadius = 6.5f;
	private Point3df center = new Point3df(0.0f, 0.0f, 0.0f);
	
	public Ball getBall() {
		return mBall;
	}
	
	/**
	* Determine is point inside game circle
	*/
	public boolean isPointInsideField(Point3df point) {
		return Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.x, 2) <= Math.pow(mRadius, 2);
	}
		
	public Point3df getClosestPointOnCircle(Point3df point) {					
	
		final double s = Math.sqrt(Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.y, 2));
		final double alpha = Math.asin(Math.abs(point.x - center.x) / s);
		
		final double dx = mRadius * Math.sin(alpha);
		final double dy = mRadius * Math.cos(alpha);
		
		Log.i("Ball", String.format("dx=%f | dy=%f", dx, dy));
		
		double x = center.x + (point.x < center.x ? -dx : +dx);
		double y = center.y + (point.y < center.y ? -dy : +dy);
		point.x = (float)x;
		point.y = (float)y;
		return point;		
	}
	
	@Override
	protected void customDraw(GL10 gl) {
		final float ambientAndDiffuse[] = {0.2f, 0.2f, 0.2f, 1.0f};
	    gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT_AND_DIFFUSE, Converter.toBuffer(ambientAndDiffuse));
	    
	    final float specular[] = {0.3f, 0.3f, 0.3f, 1.0f};
	    gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SPECULAR, Converter.toBuffer(specular));
	    gl.glMaterialf(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, 25.0f);
	    
	    final float emission[] = {0.1f, 0.2f, 0.2f, 0.3f};
	    gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_EMISSION, Converter.toBuffer(emission));
	}
}
